import React, {useState, useEffect} from 'react';
import {reqTrademarkList , reqAddTrademark , reqUpdateTrademark} from '@api/project/trademark';
import type {trademarkListType,trademarkItemType} from '@api/project/model/trademarkType';
import {Card, Button, Tooltip, Table, Modal, Form , Input , Upload ,message} from 'antd';
import style from './index.module.css';
import {DeleteOutlined, EditOutlined} from '@ant-design/icons';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';
import type { UploadChangeParam } from 'antd/es/upload';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
export default function Trademark() {
  //调用表单数据
  const [form] = Form.useForm()
  /*定义状态管理*/
  //创建品牌列表状态管理
  const [tradeList, setTradeList] = useState<trademarkListType>([]);
  //定义当前页码初始值
  const [page, setPage] = useState(1);
  //定义当前页展示的初始数量
  const [limit, setLimit] = useState(5);
  //定义加载动画
  const [isLoading, setIsLoading] = useState(false);
  //定义列表数据总数
  const [total, setTotal] = useState(0);
  //定义对话框展开和关闭的参数
  const [isModalOpen, setIsModalOpen] = useState(false);
  //创建上传图片的状态
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState<string>();
  //定义新的平拍名称
  const [newTmName , setNewTmName] = useState('');
  //定义品牌的id
  const [trademarkId,setTrademarkId] = useState(0)

  /*当组件刚刚渲染的时候就开始加载数据*/
  useEffect(() => {
    setIsLoading(true);
    getTrademarkList();
  }, [page , limit]);

  /*发送请求*/
  //1.发送请求获取tradeList数据
  const getTrademarkList = async () => {
    const re = await reqTrademarkList({
      page,
      limit,
    });
    setTradeList(re.records);
    setIsLoading(false);
    setTotal(re.total);
    // console.log('商品列表数据', re);
  };
  //2.添加新品牌的请求
  const getAddNewTrademark = async (params : trademarkItemType) =>{
    await reqAddTrademark(params)
    await getTrademarkList();
  }
  //3.修改品牌的请求
  const getUpdateTrademark = async (params : trademarkItemType) => {
    await reqUpdateTrademark(params)
    await getTrademarkList()
  }
  /*自定义函数*/
  //1.页码发生改变的回调函数
  const pageChange = (page: number, pageSize: number) => {
    setPage(page);
    setLimit(pageSize);
    getTrademarkList();
  };

  //2.控制对话框的展开和关闭
  const showModal = () => {
    setTrademarkId(0)
    setImageUrl('')
    setNewTmName('')
    setIsModalOpen(true);
  };

  const handleOk = () => {
    if (!trademarkId){
      const newTrademark = {
        tmName : newTmName,
        logoUrl : imageUrl
      }
      getAddNewTrademark(newTrademark)
      getTrademarkList()
    }else {
      const newTrademark ={
        id:trademarkId,
        tmName:newTmName,
        logoUrl:imageUrl
      }
      getUpdateTrademark(newTrademark)
      getTrademarkList()
    }
    setIsModalOpen(false);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };
  //3.上传图片的过程
  const beforeUpload = (file: RcFile) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
  };
  const handleChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
        setLoading(false);
        setImageUrl(info.file.response.data);
    }
  };
  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop:8}}>Upload</div>
    </div>
  );
  //4.获取输入框的值
  const getTmName = (e : any) =>{
    setNewTmName(e.target.value)
  }
  //5.更新数据
  const openUpdateTrade = (data : trademarkItemType) => {
    // console.log(data.tmName);
    setNewTmName(data.tmName as string)
    setImageUrl(data.logoUrl as string)
    setTrademarkId(data.id as number)
    // console.log('newTmName==>',newTmName);
    setIsModalOpen(true)
  }
  //引入table组件
  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      align: 'center' as 'center',
      render(_: any, __: any, index: number) {
        return index + 1;
      },
    },
    {
      title: '品牌名称',
      dataIndex: 'tmName',
      key: 'tmName',
      align: 'center' as 'center',
    },
    {
      title: '品牌logo',
      dataIndex: 'logoUrl',
      key: 'logoUrl',
      align: 'center' as 'center',
      render(logoUrl: string) {
        return <img width={100} src={`${logoUrl}`} alt="汗汗"/>;
      },
    },
    {
      title: '操作',
      dataIndex: 'do',
      key: 'do',
      align: 'center' as 'center',
      render(_: any, data : trademarkItemType, ___: number) {
        return (
          <div>
            <Tooltip title="修改品牌数据">
              <Button
                type="primary"
                icon={<EditOutlined/>}
                className={style.mr}
                onClick={()=>{
                  openUpdateTrade(data)
                }}
              />
            </Tooltip>
            <Tooltip title="删除品牌">
              <Button
                type="primary"
                danger
                icon={<DeleteOutlined/>}
              />
            </Tooltip>
          </div>
        );
      },
    },
  ];
  //核心页面内容
  return (
    <div className={style.outer}>
      <Card>
        <div className={style.header}>
          <Button type="primary" onClick={showModal}>添加</Button>
        </div>
        {/*对话框的位置*/}
        <Modal
          title={trademarkId?'修改':'添加'}
          open={isModalOpen}
          onOk={handleOk}
          onCancel={handleCancel}
          destroyOnClose={true}
        >
          <Form
            form={form}
            labelAlign={'left'}
            preserve={false}
          >
            <Form.Item
              label="品牌名称"
              name='tmName'
              initialValue={newTmName}
            >
              <Input onChange={getTmName}/>
            </Form.Item>
            <Form.Item
              label="品牌logo"
              name='logoUrl'
              valuePropName='file'
            >
              <Upload
                name="file"
                action="http://gmall-h5-api.atguigu.cn/admin/product/fileUpload"
                showUploadList={false}
                listType="picture-card"
                beforeUpload={beforeUpload}
                onChange={handleChange}
              >
                {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width:'100%'}} /> : uploadButton}
              </Upload>
            </Form.Item>
          </Form>
        </Modal>
        <Table
          columns={columns}
          dataSource={tradeList}
          rowKey="id"
          bordered
          loading={isLoading}
          pagination={
            {
              current: page,
              pageSize: limit,
              total,
              //展示更改每页条数的选项(默认total大于50条的时候开启)
              pageSizeOptions: [3, 8, 15],
              //是否直接开启更新每页条数的选项
              showSizeChanger: true,
              showTotal(total) {
                return `总共有${total}条数据`;
              },
              onChange: pageChange,
            }
          }
        />
      </Card>
    </div>
  );
}
